package tech.mhuang.pacebox.core.util;

import sun.misc.BASE64Encoder;
import tech.mhuang.pacebox.core.exception.BusinessException;

import javax.security.cert.CertificateException;
import javax.security.cert.X509Certificate;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;

/**
 * 证书工具类
 *
 * @author mhuang
 * @since 1.1.7
 */
public class CertificateUtil {

    /**
     *  根据证书文本获取证书
     * @param certContent 证书文本
     * @return 证书
     */
    public String getCertByContent(String certContent){
        X509Certificate cert = null;
        try {
            cert = X509Certificate.getInstance(new ByteArrayInputStream(certContent.getBytes(StandardCharsets.UTF_8)));
            PublicKey publicKey = cert.getPublicKey();
            return new BASE64Encoder().encode(publicKey.getEncoded());
        } catch (CertificateException e) {
            throw new BusinessException(e);
        }

    }
}
